package com.primeton.poctag.api.tag;

import cn.hutool.core.lang.TypeReference;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.primeton.poctag.api.BaseController;
import com.primeton.poctag.common.CommonReturn;
import com.primeton.poctag.core.model.ApiResponse;
import com.primeton.poctag.core.model.PageWrap;
import com.primeton.poctag.dao.tag.model.Tag;
import com.primeton.poctag.dto.QueryDto;
import com.primeton.poctag.service.tag.ItemRepository;
import com.primeton.poctag.service.tag.TagService;
import com.primeton.poctag.util.ConditionUtil;
import com.primeton.poctag.util.RestApiUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.plugins.PluginsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * POC标签表接口
 * @author 李功林
 * @date 2021/08/19 14:47
 */
@RestController
@RequestMapping("/tag")
public class TagController extends BaseController {
    private static final Logger logger = LogManager.getLogger(TagController.class);

    @Autowired
    private TagService tagService;
    @Autowired
    private ItemRepository itemRepository;

    @Value("${esIp}")
    private String esIp;

    /**
     * 创建
     * @author 李功林
     * @date 2021/08/19 14:47
     */
    @PostMapping("/create")
    public ApiResponse create(@RequestBody Tag tag) {
        return ApiResponse.success(tagService.create(tag));
    }

    /**
     * 用户删除
     * @author 李功林
     * @date 2021/08/19 14:47
     */
    @GetMapping("/delete/{id}")
    public ApiResponse deleteById(@PathVariable String id) {
        tagService.deleteById(id);
        return ApiResponse.success(null);
    }

    /**
     * 修改用户
     * @author 李功林
     * @date 2021/08/19 14:47
     */
    @PostMapping("/updateById")
    public ApiResponse updateById(@RequestBody Tag tag) {
        tagService.updateById(tag);
        return ApiResponse.success(null);
    }

    /**
     * 分页查询
     * @author 李功林
     * @date 2021/08/19 14:47
     */
    @PostMapping("/page")
    public ApiResponse findPage (@RequestBody PageWrap<Tag> pageWrap) {
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        // 添加基本分词查询
        queryBuilder.withQuery(QueryBuilders.matchQuery("client_name", "赵平西"));
        // 搜索，获取结果
        Page search = this.itemRepository.search(queryBuilder.build());
        return ApiResponse.success(tagService.findPage(pageWrap));
    }
    /**
     * 分页查询
     * @author 李功林
     * @date 2021/08/19 14:47
     */
    @GetMapping("/tree")
    public ApiResponse getTree () {
        return ApiResponse.success(tagService.getTree("0"));
    }

    /**
     * 通过ID查询
     * @author 李功林
     * @date 2021/08/19 14:47
     */
    @GetMapping("/{id}")
    public ApiResponse finById(@PathVariable String id) {
        return ApiResponse.success(tagService.findById(id));
    }

    @PostMapping("/tagPage")
    public ApiResponse tagPage(@RequestBody List<QueryDto> queryDto) throws IOException {
        String allSql = ConditionUtil.createSql(queryDto,1);
        logger.debug(allSql);
        Map<String, Object> result = RestApiUtils.post(esIp, allSql, false);
        if(result.get("status_code").equals(200)){
            JSONObject hits = (JSONObject) result.get("hits");
            JSONArray hits1 = (JSONArray) hits.get("hits");
            List<Object> data = hits1.stream().map(item -> ((JSONObject) item).get("_source")).collect(Collectors.toList());
            return ApiResponse.success(new CommonReturn(data,Integer.parseInt(hits.get("total").toString())));
        }
        return ApiResponse.failed();
    }
    @GetMapping("/count")
    public ApiResponse count(@RequestBody List<QueryDto> queryDto) throws IOException {
        String allSql = ConditionUtil.createSql(queryDto,2);
        Map<String, Object> result = RestApiUtils.post(esIp, allSql, false);
        if(result.get("status_code").equals(200)){
            Map<String,Object> hits = JSONObject.parseObject(result.get("hits").toString(), new TypeReference<Map<String, Object>>() {
            });
            return ApiResponse.success(hits.get("total"));
        }
        return ApiResponse.failed();
    }

}



